package com.kaifamiao.month03.day0331.bank.util;

import com.kaifamiao.month03.day0331.bank.model.Account;

import java.util.Arrays;

public class ArrayListForAccount {

    Account[] accounts = new Account[10];
    int count = 0;

    // 存储元素
    public void add(Account account) {
        grow();
        accounts[count++] = account;
    }

    // 扩容
    private void grow() {
        if (count == accounts.length) {
            accounts = Arrays.copyOf(accounts, count << 1);
        }
    }

    // 检查登录注册
    public Account isRight(String phone, String pass) {
        for (int i = 0; i < count; i++) {
            if (pass.equals(accounts[i].getPass()) && phone.equals(accounts[i].getPhone())) {
                return accounts[i];
            }
        }
        return null;
    }

    // 通过电话查找元素
    public Account getAccount(String phone) {
        for (int i = 0; i < count; i++) {
            if (phone.equals(accounts[i].getPhone())) {
                return accounts[i];
            }
        }
        return null;
    }

    // 根据下标查找元素
    public Account indexOf(int index) {
        if (checkIndex(index)) return accounts[index];
        else return null;
    }

    // 检查下标是否合法
    private boolean checkIndex(int index) {
        return index < count;
    }

    // 通过下标删除元素
    public Account remove(int index) {
        Account account = indexOf(index);
        Account[] newAccounts =  Arrays.copyOf(accounts,count);
        for (int i = index + 1; i < count; i++) {
            newAccounts[i - 1] = accounts[i];
        }
        accounts = newAccounts;
        accounts[-- count] = null;
        return account;
    }

    // 查询所有元素
    public Account[] findAll() {
        return Arrays.copyOf(accounts, count);
    }

    // 查询元素所在下标
    public int getIndex(Account account) {
        for (int i = 0; i < count; i++) {
            if (account.equals(accounts[i]))
                return i;
        }
        return -1;
    }
}
